# -*- coding: utf-8 -*-

from django.shortcuts import render_to_response
from django.http import HttpResponseRedirect, HttpResponse
from django.template import Context, Template

from cuestionarios.main.views import standard_vars, set_content_type

import access
from forms import NewMyForm, NewQuestion, NewAnswer, UpdateText

# -------------------

dict_questions = {}
dict_answers = {}

# WEB WEB WEB WEB WEB WEB WEB WEB WEB WEB WEB WEB WEB WEB WEB WEB WEB WEB WEB WEB WEB WEB WEB WEB WEB WEB WEB WEB 

def my_forms(request):
    # Variables
    vars = standard_vars(request)

    if not vars['authenticated'] or vars['is_wap']:
        return HttpResponseRedirect('/error/')

    vars["myforms"] = access.get_my_forms(request.user.id)
    
    response = render_to_response('my_forms.html', vars )
    set_content_type(vars['is_wap'], response)

    return response

# -------------------

def new_forms(request):
    # Variables
    vars = standard_vars(request)

    if not vars['authenticated'] or vars['is_wap']:
        return HttpResponseRedirect('/error/')

    if request.method == 'POST' :
        new_title = request.POST.get('titulo', None)
        if new_title:
            access.new_my_form(request.user.id, new_title)
            return HttpResponseRedirect('/my_forms/')

    vars['form'] = NewMyForm()

    response = render_to_response('new_forms.html', vars )
    set_content_type(vars['is_wap'], response)

    return response

# -------------------

def edit_form(request, myform_id):
    myform_id = int(myform_id)

    # Variables
    vars = standard_vars(request)

    if not vars['authenticated'] or vars['is_wap']:
        return HttpResponseRedirect('/error/')

    vars['valid'] = access.myform_exists(myform_id, request.user.id)

    if vars['valid']:
        vars['myform'] = myform_id
        vars['title'] = access.get_my_form_title(myform_id)
        vars['questions'] = access.get_questions_for_edit(myform_id)

    response = render_to_response('edit_form.html', vars )
    set_content_type(vars['is_wap'], response)

    return response

#----------------------------------

def add_question(request, myform_id):
    myform_id = int(myform_id)

    # Variables
    vars = standard_vars(request)

    if not vars['authenticated'] or vars['is_wap']:
        return HttpResponseRedirect('/error/')

    if request.method == 'POST' :
        question_text = request.POST.get('pregunta', None)
        correct_answer = request.POST.get('respuesta_correcta', None)
        if not question_text:
            question_text = "¿Nueva pregunta?"
        if not correct_answer:
            correct_answer = "Respuesta correcta"

        access.add_question(myform_id, question_text, correct_answer)
        return HttpResponseRedirect('/edit_form/%s/' % (myform_id,) )

    vars['valid'] = access.myform_exists(myform_id, request.user.id)

    if vars['valid']:
        vars['myform'] = myform_id
        vars['title'] = access.get_my_form_title(myform_id)
        vars['form'] = NewQuestion()

    response = render_to_response('add_question.html', vars )
    set_content_type(vars['is_wap'], response)

    return response    

#----------------------------------

def edit_question(request, myform_id, question_id):
    myform_id = int(myform_id)
    question_id = int(question_id)

    # Variables
    vars = standard_vars(request)

    if not vars['authenticated'] or vars['is_wap']:
        return HttpResponseRedirect('/error/')


    if request.method == 'POST' :
        answer_text = request.POST.get('respuesta_nueva', None)
        if not answer_text:
            answer_text = "Nueva respuesta"
        access.add_answer(question_id, answer_text)
        return HttpResponseRedirect('/edit_question/%s/%s/' % (myform_id, question_id) )

    vars['valid'] = access.myform_exists(myform_id, request.user.id) and access.question_exists(question_id)
    
    available = 8 - access.number_of_answers(question_id)
    vars['available'] = available > 0
    
    if vars['valid']:
        # MyForm
        vars['myform'] = myform_id
        vars['title'] = access.get_my_form_title(myform_id)
        # Question
        vars['question_id'] = question_id
        vars['question_text'] = access.get_question_text(question_id)
        # Respuestas
        vars['answers'] = access.get_nice_answers(question_id)
        vars['more_available'] = available
        if vars['available']:
            vars['form'] = NewAnswer()

    response = render_to_response('edit_question.html', vars )
    set_content_type(vars['is_wap'], response)

    return response

#----------------------------------

def delete_answer(request, myform_id, question_id, answer_id):
    myform_id = int(myform_id)
    question_id = int(question_id)
    answer_id = int(answer_id)

    # Variables
    vars = standard_vars(request)

    if not vars['authenticated'] or vars['is_wap']:
        return HttpResponseRedirect('/error/')


    vars['valid'] = access.myform_exists(myform_id, request.user.id) and access.question_exists(question_id)
    
    if vars['valid']:
        access.delete_answer(answer_id)
        return HttpResponseRedirect('/edit_question/%s/%s/' % (myform_id, question_id) )
    else:
        return HttpResponseRedirect('/home/')

#----------------------------------       

def delete_question(request, myform_id, question_id):
    myform_id = int(myform_id)
    question_id = int(question_id)

    # Variables
    vars = standard_vars(request)

    if not vars['authenticated'] or vars['is_wap']:
        return HttpResponseRedirect('/error/')

    vars['valid'] = access.myform_exists(myform_id, request.user.id) and access.question_exists(question_id)
    
    if vars['valid']:
        access.delete_question(question_id)
        return HttpResponseRedirect('/edit_form/%s/' % (myform_id,) )
    else:
        return HttpResponseRedirect('/home/')

#----------------------------------       

def delete_my_form(request, myform_id):
    myform_id = int(myform_id)

    # Variables
    vars = standard_vars(request)

    if not vars['authenticated'] or vars['is_wap']:
        return HttpResponseRedirect('/error/')

    vars['valid'] = access.myform_exists(myform_id, request.user.id)
    
    if vars['valid']:
        access.delete_my_form(myform_id)
        return HttpResponseRedirect('/my_forms/')
    else:
        return HttpResponseRedirect('/home/')

#----------------------------------

def update_answer(request, myform_id, question_id, answer_id):
    myform_id = int(myform_id)
    question_id = int(question_id)
    answer_id = int(answer_id)

    # Variables
    vars = standard_vars(request)

    if not vars['authenticated'] or vars['is_wap']:
        return HttpResponseRedirect('/error/')

    if request.method == 'POST' :
        new_text = request.POST.get('nuevo_texto', None)
        if new_text:
            access.set_answer_text(answer_id, new_text)
        return HttpResponseRedirect('/edit_question/%s/%s/' % (myform_id, question_id) )

    vars['valid'] = access.myform_exists(myform_id, request.user.id) and access.question_exists(question_id)
    
    if vars['valid']:
        # MyForm
        vars['myform'] = myform_id
        vars['title'] = access.get_my_form_title(myform_id)
        # Question
        vars['question_id'] = question_id
        vars['question_text'] = access.get_question_text(question_id)
        # Cambio de valor
        vars['update_field'] = "Actualizar la respuesta."
        vars['original_text'] =  "La respuesta original es: " + access.get_answer_text(answer_id)
        vars['previous_text'] =  "editar la pregunta"
        vars['previous'] = '/edit_question/%s/%s/' % (myform_id, question_id)
        vars['form'] = UpdateText()
        vars['button_text'] = "Cambia la respuesta."

    response = render_to_response('update.html', vars )
    set_content_type(vars['is_wap'], response)

    return response

#----------------------------------

def update_question(request, myform_id, question_id):
    myform_id = int(myform_id)
    question_id = int(question_id)

    # Variables
    vars = standard_vars(request)

    if not vars['authenticated'] or vars['is_wap']:
        return HttpResponseRedirect('/error/')

    if request.method == 'POST' :
        new_text = request.POST.get('nuevo_texto', None)
        if new_text:
            access.set_question_text(question_id, new_text)
        return HttpResponseRedirect('/edit_form/%s/' % (myform_id,) )

    vars['valid'] = access.myform_exists(myform_id, request.user.id) and access.question_exists(question_id)
    
    if vars['valid']:
        # MyForm
        vars['myform'] = myform_id
        vars['title'] = access.get_my_form_title(myform_id)
        # Cambio de valor
        vars['update_field'] = "Actualizar la pregunta."
        vars['original_text'] =  "La pregunta original es: " + access.get_question_text(question_id)
        vars['previous_text'] =  "editar la pregunta"
        vars['previous'] = '/edit_form/%s/' % (myform_id,)
        vars['form'] = UpdateText()
        vars['button_text'] = "Cambia la pregunta."

    response = render_to_response('update.html', vars )
    set_content_type(vars['is_wap'], response)

    return response

#----------------------------------

def update_my_form(request, myform_id):
    myform_id = int(myform_id)

    # Variables
    vars = standard_vars(request)

    if not vars['authenticated'] or vars['is_wap']:
        return HttpResponseRedirect('/error/')

    if request.method == 'POST' :
        new_text = request.POST.get('nuevo_texto', None)
        if new_text:
            access.set_my_form_text(myform_id, new_text)
        return HttpResponseRedirect('/my_forms/')

    vars['valid'] = access.myform_exists(myform_id, request.user.id)
    
    if vars['valid']:
        # MyForm
        vars['myform'] = myform_id
        # Cambio de valor
        vars['update_field'] = "Actualizar mi cuestionario."
        vars['original_text'] =  "El titulo original es: " + access.get_my_form_title(myform_id)
        vars['previous_text'] =  "mis cuestionarios"
        vars['previous'] = '/my_forms/'
        vars['form'] = UpdateText()
        vars['button_text'] = "Cambia el titulo."

    response = render_to_response('update.html', vars )
    set_content_type(vars['is_wap'], response)

    return response

#----------------------------------

def change_valid_answer(request, myform_id, question_id, answer_id):
    myform_id = int(myform_id)
    question_id = int(question_id)
    answer_id = int(answer_id)

    # Variables
    vars = standard_vars(request)

    if not vars['authenticated'] or vars['is_wap']:
        return HttpResponseRedirect('/error/')

    vars['valid'] = access.myform_exists(myform_id, request.user.id) and access.question_exists(question_id)

    if vars['valid']:
        access.change_valid_answer(question_id, answer_id)

    return HttpResponseRedirect('/edit_question/%s/%s/' % (myform_id, question_id) )


# WAP WAP WAP WAP WAP WAP WAP WAP WAP WAP WAP WAP WAP WAP WAP WAP WAP WAP WAP WAP WAP WAP WAP WAP WAP WAP WAP WAP 

def view_forms(request):
    
    vars = standard_vars(request)

    if not vars['authenticated'] or not vars['is_wap']:
        return HttpResponseRedirect('/error/')
        
    vars["allforms"] = access.get_all_forms(request.user.id)
    
    response = render_to_response('all_forms.html', vars )
    set_content_type(vars['is_wap'], response)
    
    return response

#---------------------------------- 

def contestar(request,f_id):
    vars = standard_vars(request)

    if not vars['authenticated'] or not vars['is_wap']:
        return HttpResponseRedirect('/error/')
        
    question_list = access.get_questions(f_id)
    dict_questions[request.user.id] = question_list
    dict_answers[request.user.id] = [len(question_list),0]
    
    if dict_questions[request.user.id]:     
        question_tuple = dict_questions[request.user.id].pop()
        vars["question_text"] = question_tuple[0]
        vars["question_id"] = question_tuple[1]
        vars["form_id"] = f_id
        answer_list = []
        for answer in access.get_answer_list(question_tuple[1]):
            answer_list.append((answer.id,answer.text))
        vars["answers"] = answer_list
    else:
         vars["question_text"] = "Este cuestionario no tiene preguntas."
    
    response = render_to_response('contestando.html', vars )
    set_content_type(vars['is_wap'], response)
    
    return response
   
#----------------------------------       

def ajax_next(request, f_id):
    vars = standard_vars(request)

    if not vars['authenticated'] or not vars['is_wap']:
        return HttpResponseRedirect('/error/')       

    u_id = request.user.id
    question_list = dict_questions[request.user.id]
    print question_list    
    if question_list:
        question_tuple = dict_questions[request.user.id].pop()
        vars["question_text"] = question_tuple[0]
        vars["question_id"] = question_tuple[1]
        vars["form_id"] = f_id
        answer_list = []
        for answer in access.get_answer_list(question_tuple[1]):
            answer_list.append((answer.id,answer.text))
        vars["answers"] = answer_list
        response = render_to_response('contestando.html', vars )
        set_content_type(vars['is_wap'], response)
    else:
        print dict_answers[request.user.id][1]
        response = HttpResponseRedirect('/form_stats/'+f_id+'/')
    
    return response

#----------------------------------
        
def ajax(request):
    a_id = request.POST.get('answers', '')
    q_id = request.POST.get('question','')
    f_id = request.POST.get('form','')
    next = '<a href = "/siguiente_ajax/'+f_id+'">Siguiente pregunta</a>'
    
    
    if (access.is_correct(a_id)):
        dict_answers[request.user.id][1] += 1
        return HttpResponse("<strong> Correcto </strong><br />%s" % (next,)
                            , mimetype="text/plain")
    else:
        correct_answer = access.get_correct_answer(q_id)
	t = Template('<strong> Error! </strong> La respuesta correcta es : <strong> {{ respuesta_correcta|escape }} </strong><br />')
	c = Context({'respuesta_correcta': correct_answer})
        return HttpResponse( t.render(c) + next , mimetype="text/plain")

#----------------------------------  

def form_stats(request,f_id):
    vars = standard_vars(request)
    
    if not vars['authenticated'] or not vars['is_wap']:
        return HttpResponseRedirect('/error/')
        
    vars['total_questions'] = dict_answers[request.user.id][0]
    vars['total_correct'] = dict_answers[request.user.id][1]
    vars['average'] = (dict_answers[request.user.id][1]*100)/dict_answers[request.user.id][0]
    access.add_stats(f_id, request.user.id, vars['total_questions'], vars['total_correct'] )
   
    response = render_to_response('estadisticas.html', vars )
    set_content_type(vars['is_wap'], response)
    return response
    
#----------------------------------

def mystats(request):
    vars = standard_vars(request)
    
    if not vars['authenticated'] or not vars['is_wap']:
        return HttpResponseRedirect('/error/')
        
    vars['totalidad'] = access.get_forms_from_user(request.user.id)
    response = render_to_response('my_stats.html', vars )
    set_content_type(vars['is_wap'], response)
    return response

